package service

import (
	"gitee.com/molonglove/goboot/gorm"
	"helper-api/app/models/entity"
	"helper-api/app/models/request"
	"helper-api/app/models/response"
	"helper-api/core"
	"helper-api/utils"
	"time"
)

var Permission = new(PermissionService)

type PermissionService struct{}

// CreatePermission 创建资源
func (s *PermissionService) CreatePermission(param request.ResourceCreateRequest) (*response.PermissionListResponse, *response.BusinessError) {
	var (
		result *entity.Permission
		total  int64
		err    error
	)
	if err = core.DB.Model(&entity.Permission{}).
		Where("can_view = 1 and name = ? and code = ?", param.Name, param.Code).
		Count(&total).
		Error; err != nil {
		core.Log.Error("执行SQL错误 => %s", err.Error())
		return nil, response.NewBusinessError(response.SqlExecuteError)
	}
	if total > 0 {
		core.Log.Error("查询到相同的数据 => %d条", total)
		return nil, response.NewBusinessError(response.ExistSameData)
	}
	result = &entity.Permission{
		Name:       param.Name,
		Code:       param.Code,
		Icon:       param.Icon,
		Brief:      param.Brief,
		ParentId:   param.ParentId,
		Path:       param.Path,
		Level:      param.ResType,
		ResType:    param.ResType,
		CreateId:   param.UserId,
		CreateTime: time.Now(),
		CanView:    1,
	}
	if err = core.DB.Model(&entity.Permission{}).Create(result).Error; err != nil {
		core.Log.Error("执行SQL错误 => %s", err.Error())
		return nil, response.NewBusinessError(response.ResourceCreateError)
	}
	return &response.PermissionListResponse{
		Id:         result.Id,
		Name:       result.Name,
		Code:       result.Code,
		ParentId:   result.ParentId,
		Icon:       result.Icon,
		Path:       result.Path,
		ResType:    result.ResType,
		UserId:     result.CreateId,
		Username:   "",
		Level:      result.Level,
		OrderNo:    result.OrderNo,
		CreateTime: result.CreateTime,
	}, nil
}

// UpdatePermission 更新资源
func (s *PermissionService) UpdatePermission(param request.ResourceUpdateRequest) (*response.PermissionListResponse, *response.BusinessError) {
	var (
		result entity.Permission
		err    error
	)
	if err = core.DB.Model(&entity.Permission{}).
		Where("id = ? and can_view = 1", param.Id).
		First(&result).
		Error; err != nil {
		core.Log.Error("执行SQL查询错误 => %s", err.Error())
		return nil, response.NewBusinessError(response.SqlExecuteError)
	}
	result.Name = param.Name
	result.Code = param.Code
	result.Path = param.Path
	result.Icon = param.Icon
	result.Brief = param.Brief
	result.OrderNo = param.OrderNo
	result.ResType = param.ResType
	result.Level = param.ResType
	result.UpdateId = param.UserId
	result.UpdateTime = time.Now()
	if err = core.DB.Save(&result).Error; err != nil {
		core.Log.Error("执行SQL更新错误 => %s", err.Error())
		return nil, response.NewBusinessError(response.SqlExecuteError)
	}
	return &response.PermissionListResponse{
		Id:         result.Id,
		Name:       result.Name,
		Code:       result.Code,
		ParentId:   result.ParentId,
		Icon:       result.Icon,
		Path:       result.Path,
		ResType:    result.ResType,
		UserId:     result.CreateId,
		Username:   "",
		Level:      result.Level,
		OrderNo:    result.OrderNo,
		CreateTime: result.CreateTime,
	}, nil
}

// Tree 查询资源
func (s *PermissionService) Tree(pId int64, all bool) ([]response.PermissionTreeProp, *response.BusinessError) {
	var (
		db     *gorm.DB
		list   []response.PermissionTreeProp
		result []response.PermissionTreeProp
		filter = func(list []response.PermissionTreeProp, pId int64) []response.PermissionTreeProp {
			result := make([]response.PermissionTreeProp, 0)
			for _, item := range list {
				if item.ParentId == pId {
					result = append(result, item)
				}
			}
			return result
		}
		err error
	)
	db = core.DB.Debug().Model(&entity.Permission{})
	if all {
		db.Select("s_permission.id as key, s_permission.level, s_permission.name as title, s_permission.res_type as types, s_permission.parent_id").
			Where("s_permission.can_view = 1")
	} else {
		db.Select("s_permission.id as key, s_permission.level, s_permission.name as title, s_permission.res_type as types, (select count(sp2.id) from s_permission sp2 where sp2.parent_id = s_permission.id) as num").
			Where("s_permission.parent_id = ? and s_permission.can_view = 1", pId)
	}
	if err = db.Order("s_permission.order_no").Find(&list).Error; err != nil {
		core.Log.Error("执行SQL更新错误 => %s", err.Error())
		return list, response.NewBusinessError(response.SqlExecuteError)
	}
	if all {
		// 这里层级只有三层，for循环构建tree
		result = filter(list, 0)
		for i := 0; i < len(result); i++ {
			temp := filter(list, result[i].Key)
			if len(temp) > 0 {
				result[i].IsLeaf = false
				result[i].Children = temp
				for j := 0; j < len(temp); j++ {
					innerTemp := filter(list, temp[j].Key)
					if len(innerTemp) > 0 {
						for x := 0; x < len(innerTemp); x++ {
							innerTemp[x].IsLeaf = true
						}
						result[i].Children[j].Children = innerTemp
						result[i].Children[j].IsLeaf = false
					} else {
						result[i].Children[j].IsLeaf = true
					}
				}
			} else {
				result[i].IsLeaf = true
			}
		}
		return result, nil
	} else {
		for i := 0; i < len(list); i++ {
			list[i].IsLeaf = !(list[i].Num > 0)
		}
	}
	return list, nil
}

// DeleteResource 删除资源
func (s *PermissionService) DeleteResource(ids []int64, id int64) *response.BusinessError {
	if err := core.DB.Model(&entity.Permission{}).
		Where("id in ?", ids).
		Updates(map[string]interface{}{"update_id": id, "update_time": time.Now(), "can_view": 0}).
		Error; err != nil {
		core.Log.Error("执行SQL删除错误 => %s", err.Error())
		return response.NewBusinessError(response.SqlExecuteError)
	}
	return nil
}

// List 资源列表
func (s *PermissionService) List(id int64) ([]response.PermissionListResponse, *response.BusinessError) {
	var (
		list []response.PermissionListResponse
		err  error
	)
	if err = core.DB.Debug().Model(&entity.Permission{}).
		Select("s_permission.id,s_permission.name,s_permission.code,s_permission.parent_id,s_permission.icon,s_permission.res_type,s_permission.create_id as user_id,s_permission.level,s_permission.create_time,s_user.username,s_permission.order_no,s_permission.path").
		Joins("left join s_user on s_user.id = s_permission.create_id").
		Where("s_permission.can_view = 1 and s_permission.parent_id = ?", id).
		Order("order_no").
		Find(&list).
		Error; err != nil {
		core.Log.Error("执行SQL删除错误 => %s", err.Error())
		return list, response.NewBusinessError(response.SqlExecuteError)
	}
	return list, nil
}

// Info 详情
func (s *PermissionService) Info(id int64) (response.PermissionInfoResponse, *response.BusinessError) {
	var (
		users      []entity.User
		permission entity.Permission
		parent     entity.Permission
		info       response.PermissionInfoResponse
		err        error
	)
	if err = core.DB.
		Model(&entity.Permission{}).
		Where("id = ? and can_view = 1", id).
		First(&permission).
		Error; err != nil {
		return info, response.NewBusinessError(response.DataNotExist)
	}
	_ = utils.StructCopy(permission, &info)
	if permission.ParentId != 0 {
		if err = core.DB.
			Model(&entity.Permission{}).
			Where("id = ? and can_view = 1", id).
			First(&parent).
			Error; err == nil {
			info.ParentId, info.ParentName = permission.ParentId, parent.Name
		}
	}
	if err = core.DB.Model(&entity.User{}).
		Where("can_view = 1 and id in ()", []int64{permission.CreateId, permission.UpdateId}).
		Find(&users).
		Error; err == nil {
		for _, user := range users {
			if user.Id == permission.CreateId {
				info.UserId, info.Username = user.Id, user.Username
			}
			if user.Id == permission.UpdateId {
				info.UpdateId, info.UpdateName = user.Id, user.Username
			}
		}
	}
	return info, nil
}
